﻿using System;
using System.Collections.Generic;
using System.Text;
using Vbyte.TextReader.Util;

namespace Vbyte.TextReader
{
    /// <summary>
    /// 接口错误日志阅读器
    /// </summary>
    public class APIErrorLogReader : LogReader<APIErrorLog>
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="APIErrorLogReader"/> class.
        /// </summary>
        /// <param name="logDir">日志存放目录</param>
        /// <param name="whichDay">日志阅读的日期</param>
        public APIErrorLogReader(string logDir, DateTime whichDay)
            : base(logDir, new string[] { "^Error-API-(?<Date>\\d{4}\\-\\d{2}\\-\\d{2})" }, whichDay)
        {

        }

        /// <summary>
        /// 前进阅读，表示当前日志是否可读。
        /// </summary>
        /// <returns>如果返回为true，则还有数据需要阅读。</returns>
        public override bool Read()
        {
            bool result = CanRead();
            if (!result)
            {
                _current = null;
            }
            else
            {

            //读取实例数据开始
            ReadInstanceLog:

                string lineStr = Reader.ReadLine();
                if (lineStr == null)
                {
                    _current = null;
                    result = false;
                }
                else
                {
                    _current = new APIErrorLog();

                    string[] tArr = StringHelper.GetPatternMatchValue(lineStr, "@\\s(\\d{4}\\-\\d{2}\\-\\d{2}\\s\\d{2}:\\d{2}\\:\\d{2},\\d{3})\\s", 1);
                    if (tArr != null)
                    {
                        _current.LogTime = DateTime.ParseExact(tArr[0], "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                    }

                    StringBuilder logBuilder = new StringBuilder(lineStr);
                    logBuilder.AppendLine();

                    #region 逐行设置实例属性
                    while ((lineStr = Reader.ReadLine()) != null)
                    {
                        if (lineStr.StartsWith("---TimeFlag"))
                        {
                            Reader.GotoLastLine();
                            break;
                        }
                        else
                        {
                            if (lineStr.StartsWith("标志参数："))
                            {
                                _current.JSONIdentity = lineStr.Substring("标志参数：".Length);
                            }
                            else if (lineStr.StartsWith("获取数据异常："))
                            {
                                _current.TargetInstance = lineStr.Substring("获取数据异常：".Length);
                            }

                            logBuilder.Append(lineStr);
                            logBuilder.AppendLine();
                        }
                    }
                    #endregion

                    #region 检查内容判断是否正确，否则修改编码为UTF-8重读
                    if (string.IsNullOrEmpty(_current.TargetInstance))
                    {
                        Reader.ContentEncoding = Encoding.UTF8;
                        Reader.GotoLastMatchLine(m => m.Contains("-TimeFlag @"));
                        goto ReadInstanceLog;
                    }
                    #endregion

                    string logStr = logBuilder.ToString();
                    //Console.WriteLine(logStr);
                    logStr = StringHelper.GetSnippetBlock(ref logStr, "消息：", "错误", "堆栈信息：");
                    if (logStr.Length > 10)
                    {
                        _current.Message = logStr.Substring(5, logStr.Length - 10).TrimEnd('\n', '\r');
                    }

                    _current.LogCursor = String.Format("{0}-{1}", base.CurrentFileIndex, base.Reader.GetPosition());
                }
            }
            return result;
        }


        private APIErrorLog _current = null;


        /// <summary>
        /// 阅读器当前实例
        /// </summary>
        /// <returns>返回阅读器当前所在的实例</returns>
        public override APIErrorLog GetCurrent()
        {
            return _current;
        }
    }

    /// <summary>
    /// 接口错误日志
    /// </summary>
    [Serializable]
    public class APIErrorLog : ILogItemTime
    {

        /// <summary>
        /// 目标数据类型
        /// </summary>
        public string TargetInstance { get; set; }

        /// <summary>
        /// JSON数据标志
        /// </summary>
        public string JSONIdentity { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 日志时间
        /// </summary>
        /// <value></value>
        public DateTime LogTime
        {
            get;
            set;
        }

        /// <summary>
        /// 日志游标位置
        /// </summary>
        /// <value></value>
        public string LogCursor
        {
            get;
            set;
        }

    }
}
